<script setup>
import { ref, onBeforeUnmount } from 'vue'
import { getHasSpuAPI, getSkuInfoAPI, removeSpuAPI } from '@/api/product/spu'
import { watch } from 'vue'
import useCategoruStore from '@/store/modules/category'
import SkuForm from './skuForm.vue'
import SpuForm from './spuForm.vue'
import { ElMessage } from 'element-plus'

const categoryStore = useCategoruStore()

// 场景切换控制变量
const editShowFlag = ref(0) // 0表示spu展示界面， 1表示spu属性编辑界面， 2表示sku属性编辑界面

// 默认当前页
const currentPage = ref(1)

// 每页显示条数
const pageSize = ref(10)

// 已有SPU数据
const spuArr = ref([])

// 总条数
const total = ref(0)

// 获取spuForm实例
const spu = ref()

watch(() => categoryStore.c3Id, () => {
  if(!categoryStore.c3Id) {return}
  getHasSpu()
})

// 获取SPU数据
const getHasSpu = async (page = 1) => {
  currentPage.value = page
  let res = await getHasSpuAPI(currentPage.value, pageSize.value, categoryStore.c3Id)
  if(res.code === 200) {
    spuArr.value = res.data.records
    total.value = res.data.total
  }
}

// 页码发生变化的钩子函数
const pageHandler = (currentPage) => {
  getHasSpu(currentPage)
}

// 添加Spu
const addSpu = () => {
  // 切换到spu添加界面
  editShowFlag.value = 1
  // 点击添加spu按钮，调用子组件的方法初始化数据
  spu.value.initAddSpu(categoryStore.c3Id)
}

// 修改Spu
const updateSpu = (row) => {
  // 切换到spu编辑界面
  editShowFlag.value = 1
  spu.value.getSpu(row)
}

// 取消时切换场景
const changeScene = (obj) => {
  // 切换到spu显示界面
  editShowFlag.value = obj.flag
  // 再次获取更新的已有SPU
  if(obj.mode === 'update') {
    // 为更新留在当前页
    getHasSpu(currentPage.value)
  } else {
    // 为添加回到第一页
    getHasSpu()
  }
}

// 获取子组件实例skuform
const sku = ref()

// 添加sku
const addSku = (row) => {
  // 点击按钮，切换场景为2
  editShowFlag.value = 2
  // 调用子组件的方法初始化添加SKU的数据
  sku.value.initSkuData(categoryStore.c1Id, categoryStore.c2Id, categoryStore.c3Id, row)
}

// 存储sku数据
const skuArr = ref([])

// 控制sku对话框显示隐藏
const skuDialogShow = ref(false)

// 查看sku
const findSku = async (row) => {
  let res = await getSkuInfoAPI(row.id)
  if(res.code === 200) {
    skuArr.value = res.data
    // 对话框显示出来
    skuDialogShow.value = true
  }
}

// 删除spu
const removeSpu = async (row) => {
  let res = await removeSpuAPI(row.id)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除SPU成功'
    })
    // 拉取新的spu数据，要根据当前数据长度判断拉取哪一页的数据
    getHasSpu(spuArr.value.length > 1 ? currentPage.value : currentPage.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除SPU失败'
    })
  }
}

// 路由组件销毁前，清空仓库关于分类的数据
onBeforeUnmount(() => {
   // 清空仓库的数据
  categoryStore.c1Arr = []
  categoryStore.c2Arr = []
  categoryStore.c3Arr = []
  categoryStore.c1Id = null
  categoryStore.c2Id = null
  categoryStore.c3Id = null
})
</script>

<template>
  <div>
    <Category :disableFlag="editShowFlag"></Category>
    <el-card style="margin: 10px 0;">
      <div v-show="editShowFlag === 0">
        <el-button type="primary" size="default" icon="Plus" :disabled="!categoryStore.c3Id" @click="addSpu">添加SPU</el-button>
        <el-table border style="margin: 10px 0;" :data="spuArr">
          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="SPU名称" prop="spuName"/>
          <el-table-column label="SPU描述" prop="description" show-overflow-tooltip/>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="primary" size="default" icon="Plus" title="添加SKU" @click="addSku(row)"></el-button>
              <el-button type="warning" size="default" icon="Edit" title="修改SPU" @click="updateSpu(row)"></el-button>
              <el-button type="info" size="default" icon="View" title="查看SKU" @click="findSku(row)"></el-button>
              
              <el-popconfirm
              width="200"
              :title="`你确定要删除${row.spuName}吗`"
              icon="Delete"
              @confirm="removeSpu(row)">
                <template #reference>
                  <el-button type="danger" size="default" icon="Delete" title="删除SPU"></el-button>
                </template>
              </el-popconfirm>
              
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[1, 3, 5, 7, 9]"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        :background="true"
        @change="pageHandler">
        </el-pagination>
      </div>
      <SkuForm v-show="editShowFlag === 2" @changeScene="changeScene" ref="sku"></SkuForm>
      <SpuForm v-show="editShowFlag === 1" @cancel="changeScene" ref="spu"></SpuForm>
      <!-- dialog对话框： 展示已有的sku数据 -->
      <el-dialog
      title="SKU列表"
      v-model="skuDialogShow"
      width="30%">
        <el-table border :data="skuArr">
          <el-table-column label="SKU名字" prop="skuName"></el-table-column>
          <el-table-column label="SKU价格" prop="price"></el-table-column>
          <el-table-column label="SKU重量" prop="weight"></el-table-column>
          <el-table-column label="SKU图片">
            <template #default="{row}">
              <img :src="row.skuDefaultImage" style="width: 100px;height: 100px;" alt="">
            </template>
          </el-table-column>
          
        </el-table>
      </el-dialog>
      
    </el-card>
  </div>
</template>

<style scoped></style>
